package com.test.typeGame.checkUpdate;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

public class CheckUpdate extends JFrame {
    public static Logger logger = Logger.getLogger("CheckUpdate");

    JFrame c = this;

    public CheckUpdate(){
        setAttb();

        JLabel title = new JLabel("正在检查网络上的更新资源");
        this.add(title,BorderLayout.NORTH);
        JTextArea msg = new JTextArea();
        this.add(msg, BorderLayout.CENTER);
        JLabel process = new JLabel();
        this.add(process, BorderLayout.SOUTH);

        //启动线程
        new Check(msg, process).start();
    }

    private class Check extends Thread{
        private boolean isUpdated = false;
        String netVersion;
        String localVersion;
        JTextArea msg;
        JLabel process;

        String localVersionFilename = "version.txt";
        String oldFilename = "打字练习.exe";
        String newFilename = "打字练习.exe.tmp";

        public Check(JTextArea msg, JLabel process){
            this.msg = msg;
            this.process = process;
        }

        @Override
        public void run(){
            logger.info("开始升级");
            String netVersionUrl = "https://gitee.com/cloudmarket/typeGame/raw/master/deploy/version.txt";
            URL url = null;
            HttpURLConnection httpURLConnection = null;
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try{
                url = new URL(netVersionUrl);
                httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setRequestProperty("User-Agent"," Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");

                httpURLConnection.connect();
                //inputStream = url.openStream();
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                String netVersionStr = bufferedReader.readLine();
                String localVersionStr = getLocalVersion();
                if (localVersionStr.equals(netVersionStr)){
                    msg.append("当前已经是最新版本");
                    isUpdated = false;
                }else {
                    msg.append("发现新版本，现在更新");
                    isUpdated = true;
                    netVersion = netVersionStr;
                }
            }catch (Exception e){
                logger.info(e.getMessage());
            }finally {
                try {
                    bufferedReader.close();
                    inputStream.close();
                    inputStreamReader.close();
                }catch (Exception e){
                    logger.info(e.getMessage());
                }
            }

            //更新,下载网络文件，更新本地文件
            if (isUpdated){
                File oldFile = new File(oldFilename);
                File newFile = new File(newFilename);
                String updateUrl = "https://gitee.com/cloudmarket/typeGame/raw/master/deploy/%E6%89%93%E5%AD%97%E7%BB%83%E4%B9%A0.exe";

                BufferedInputStream bufferedInputStream = null;
                FileOutputStream fileOutputStream = null;
                try{
                    url = new URL(updateUrl);
                    httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setRequestProperty("User-Agent"," Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");

                    httpURLConnection.connect();
                    byte []buffer = new byte[1024];
                    int size = 0;
                    msg.append("正在下载更新文件");
                    try{
                        inputStream = httpURLConnection.getInputStream();
                        bufferedInputStream = new BufferedInputStream(inputStream);
                        fileOutputStream = new FileOutputStream(newFile);
                        int processFlag = 0;
                        int processFlag1 = 0;
                        while ((size = bufferedInputStream.read(buffer)) != -1){
                            fileOutputStream.write(buffer, 0, size);
                            fileOutputStream.flush();
                            if (processFlag1 == 99){
                                processFlag1 = 0;
                                process.setText(process.getText()+".");
                            }
                            processFlag++;
                            processFlag1++;
                            if (processFlag > ((99*50))){
                                processFlag = 0;
                                process.setText("");
                            }
                        }
                    }catch (Exception e){
                        logger.info(e.getMessage());
                    }
                    msg.append("下载文件完毕");

                    //拷贝文件
                    copyFile(oldFile, newFile);
                    //存储本地版本
                    saveLocalVersion(netVersion);

                }catch (Exception e){
                    logger.info(e.getMessage());
                }finally {
                    try {
                        inputStream.close();
                        fileOutputStream.close();
                        bufferedInputStream.close();
                        httpURLConnection.connect();
                    }catch (Exception e){
                        logger.info(e.getMessage());
                    }
                }

                if (newFile.exists()){
                    newFile.delete();
                }
                logger.info("升级完成");
            }

            try {
                msg.append("启动应用程序");
                Thread.sleep(500);
                Process process = Runtime.getRuntime().exec(oldFilename);
            }catch (Exception e){
                logger.info(e.getMessage());
            }

            //退出
            System.exit(0);
        }

        public void copyFile(File oldFile,File newFile){
            FileOutputStream fileOutputStream = null;
            FileInputStream fileInputStream = null;
            try{
                if (oldFile.exists()){
                    oldFile.delete();
                }
                fileInputStream = new FileInputStream(newFile);
                fileOutputStream = new FileOutputStream(oldFile);
                byte[]buffer = new byte[1024*5];
                int size = 0;
                while ((size = fileInputStream.read(buffer)) != -1){
                    fileOutputStream.write(buffer,0,size);
                    fileOutputStream.flush();
                }
            }catch (Exception e){
                logger.info(e.getMessage());
            }finally {
                try {
                    fileInputStream.close();
                    fileOutputStream.close();
                }catch (Exception e){
                    logger.info(e.getMessage());
                }
            }
        }

        public void saveLocalVersion(String netVersion){
            FileWriter fileWriter = null;
            BufferedWriter bufferedWriter = null;
            try{
                fileWriter = new FileWriter(localVersionFilename);
                bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(netVersion);
                bufferedWriter.flush();
            }catch (Exception e){
                logger.info(e.getMessage());
            }finally {
                try {
                    bufferedWriter.close();
                    fileWriter.close();
                }catch (Exception e){
                    logger.info(e.getMessage());
                }
            }
        }

        public String getLocalVersion(){
            //本地版本文件
            File file = new File(localVersionFilename);
            FileReader fileReader = null;
            BufferedReader bufferedReader = null;
            try{
                fileReader = new FileReader(file);
                bufferedReader = new BufferedReader(fileReader);
                String localVersionStr = bufferedReader.readLine();
                return localVersionStr;
            }catch (Exception e){
                logger.info(e.getMessage());
            }finally {
                try{
                    bufferedReader.close();
                    fileReader.close();
                }catch (Exception e){
                    logger.info(e.getMessage());
                }
            }
            return "";
        }
    }



    void setAttb(){
        this.setTitle("自动升级");
        this.setSize(200,150);
        this.setLayout(new BorderLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = this.getSize();

        if (frameSize.height > screenSize.height){
            frameSize.height = screenSize.height;
        }

        if (frameSize.width > screenSize.width){
            frameSize.width = screenSize.width;
        }

        this.setLocation((screenSize.width - frameSize.width)/2, (screenSize.height - frameSize.height)/2);
    }

    public static void main(String []args){
        CheckUpdate checkUpdate = new CheckUpdate();
        checkUpdate.setVisible(true);
    }
}
